package com.hzcx.app.simplechat.ui.group;

import android.content.Intent;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseViewHolder;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.chat.EMTextMessageBody;
import com.hzcx.app.simplechat.R;
import com.hzcx.app.simplechat.api.BaseObserver;
import com.hzcx.app.simplechat.chat.ChatUtil;
import com.hzcx.app.simplechat.model.GroupModel;
import com.hzcx.app.simplechat.model.PublicModel;
import com.hzcx.app.simplechat.ui.friend.bean.FriendCityBean;
import com.hzcx.app.simplechat.ui.friend.bean.GroupBean;
import com.hzcx.app.simplechat.ui.group.LiveData.GroupInfoBeanLiveData;
import com.hzcx.app.simplechat.ui.group.bean.GroupInfoBean;
import com.hzcx.app.simplechat.ui.group.bean.MembersBean;
import com.hzcx.app.simplechat.ui.home.HomeSearchMsgActivity;
import com.hzcx.app.simplechat.ui.home.adapter.HomeSearchMsgAdapter;
import com.hzcx.app.simplechat.ui.publicui.bean.HxUserInfoBean;
import com.hzcx.app.simplechat.ui.user.UserInfoActivity;
import com.hzcx.app.simplechat.util.UserInfoUtil;
import com.hzcx.app.simplechat.util.empty.EmptyUtils;
import com.hzcx.app.simplechat.util.glide.GlideUtils;
import com.hzcx.app.simplechat.util.log.LogUtils;
import com.hzcx.app.simplechat.util.toast.ToastUtils;

import org.litepal.LitePal;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

class GroupSearchMsgAdapter extends HomeSearchMsgAdapter {

    private List<FriendCityBean> friendData;

    public GroupSearchMsgAdapter(@Nullable List<EMMessage> data, List<FriendCityBean> friendCityBeans) {
        super(data);
        friendData = friendCityBeans;
    }

    @Override
    protected void convert(BaseViewHolder helper, EMMessage item) {

        try {
            // 设置昵称，头像
            EMMessage message = item;
            final HxUserInfoBean[] userInfoBean = new HxUserInfoBean[1];
            if (message.getChatType() == EMMessage.ChatType.Chat || message.getChatType() == EMMessage.ChatType.GroupChat) { // 单聊
                String hxusername = message.getFrom();
                LitePal.where("hxusername=? and myUserId=?", hxusername, UserInfoUtil.getUserId() + "").findFirstAsync(HxUserInfoBean.class).listen(hxUserInfoBean -> {

                    if (hxUserInfoBean == null) {
                        PublicModel.getUserInfoByHx(mContext, hxusername, new BaseObserver<HxUserInfoBean>() {
                            @Override
                            protected void onSuccess(HxUserInfoBean data) {
                                data.setHxusername(hxusername);
                                data.setMyUserId(UserInfoUtil.getUserId());
                                data.save();
                                userInfoBean[0] = data;
                                GlideUtils.loadImg(mContext, data.getAvatar(), helper.getView(R.id.iv_head));
                                if (EmptyUtils.isNotEmpty(data.getRemarks_name())) {
                                    helper.setText(R.id.tv_nick_name, data.getRemarks_name());
                                } else {
                                    helper.setText(R.id.tv_nick_name, data.getNickname());
                                }
                            }
                        });
                    } else {
                        userInfoBean[0] = hxUserInfoBean;
                        GlideUtils.loadImg(mContext, hxUserInfoBean.getAvatar(), helper.getView(R.id.iv_head));
                        if (EmptyUtils.isNotEmpty(hxUserInfoBean.getRemarks_name())) {
                            helper.setText(R.id.tv_nick_name, hxUserInfoBean.getRemarks_name());
                        } else {
                            helper.setText(R.id.tv_nick_name, hxUserInfoBean.getNickname());
                        }
                    }
                });
            } else { // room
            }

            EMTextMessageBody txtBody = (EMTextMessageBody) item.getBody();
            String str = txtBody.getMessage();
            Pattern p = Pattern.compile(key);
            Matcher m = p.matcher(str);
            String s = "";
            while (m.find()) {
                int start = m.start();
                int end = m.end();
                if (start > 7) {
                    s = "..." + str.substring(start - 7, start) + key;
                } else {
                    s = str.substring(0, start) + key;
                }
                if (str.length() - end > 7) {
                    s = s + str.substring(end, end + 7) + "...";
                } else {
                    s = s + str.substring(end);
                }
            }

            helper.setText(R.id.tv_content, findSearch(mContext.getResources().getColor(R.color.color_2D7CFD), s, key));

            // 列表点击
            helper.getView(R.id.cons_content).setOnClickListener(view -> {
                if (userInfoBean[0] == null) {
                    ToastUtils.show("用户数据异常，请稍后重试");
                    return;
                }
                if (item.getChatType() == EMMessage.ChatType.GroupChat) {
                    ChatUtil.getInstance().toGroupChatUi(mContext, userInfoBean[0]);
                } else {
                    ChatUtil.getInstance().toChatUi(mContext, userInfoBean[0]);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

public class GroupSearchMsgActivity extends HomeSearchMsgActivity {

//    static public String GroupInfoBeanKey = "GroupSearchMsgActivityGroupInfoBeanKey";
//    GroupInfoBean groupInfoBean;

    public static String GroupInfoBeanKeyGroupID = "QrCodeActivity_GroupInfoBeanKeyGroupID";
    GroupInfoBean groupInfoBean;
    private String groupID;

    @Override
    public void configSearchView() {

//        groupInfoBean = (GroupInfoBean)getIntent().getSerializableExtra(GroupInfoBeanKey);
        groupID = getIntent().getStringExtra(GroupInfoBeanKeyGroupID);
        groupInfoBean = GroupInfoBeanLiveData.getGroupInfoBean(groupID);

        List<FriendCityBean> beans = new ArrayList<>();
        for (MembersBean membersBean: groupInfoBean.getMembers()) {
            beans.add(FriendCityBean.convert(membersBean));
        }
        friendData.addAll(beans);

        searchData = new ArrayList<>();
        searchMsgAdapter = new GroupSearchMsgAdapter(searchData, friendData);
        rvSearchMsg.setLayoutManager(new LinearLayoutManager(this, RecyclerView.VERTICAL, false));
        rvSearchMsg.setAdapter(searchMsgAdapter);
    }

    @Override
    public void initData() {
        EMConversation conversation = EMClient.getInstance().chatManager().getConversation(groupInfoBean.getHx_groupid());
        messageData = new ArrayList<>();
        messageData.add(conversation);


//        // 联系人列表点击
//        try {
//            contentAdapter.setOnItemClickListener((adapter, view, position) -> startActivity(new Intent(GroupSearchMsgActivity.this, UserInfoActivity.class)
//                    .putExtra(UserInfoActivity.INTENT_USER_ID, friendData.get(position).getMember_id())));
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
    }


    /**
     * 搜索本地用户
     *
     * @param keyWord
     * @return
     */
    private void searchFriend(String keyWord) {
//        String sql = "nickname like '%" + keyWord + "%' or remarks_name like '%" + keyWord + "%'";
//        LogUtils.d("sql:" + sql);
//        LitePal.where(sql).findAsync(FriendCityBean.class).listen(list -> {
//            if (list == null || list.size() <= 0) {
//                return;
//            }
//            friendData.addAll(list);
//            contentAdapter.notifyDataSetChanged();
//            tvFriendNum.setText("共有" + friendData.size() + "个相关的联系人");
//        });
    }

}
